package com.zzt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzt.common.R;
import com.zzt.domain.Category;
import com.zzt.domain.Setmeal;
import com.zzt.domain.dto.SetmealDto;
import com.zzt.service.CategoryService;
import com.zzt.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    //allEntries = true,清除setmealCache缓存分组下所有key以及对应值
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("新增套餐{}", setmealDto);

        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询,可包含条件
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("套餐分页查询，page={}，pageSize={}，条件name={}", page, pageSize, name);

        //构造分页构造器
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Setmeal::getName, name);
        //查询获得以Setmeal为数据集合的setmealPage
        setmealService.page(setmealPage, wrapper);

        //接下来准备拷贝，为了让前端展示套餐分类
        //构造新分页构造器
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        //查找套餐分类名，对records集合数据处理后拷贝至新分页构造器的records
        List<Setmeal> records = setmealPage.getRecords();
        List<SetmealDto> newRecords = new ArrayList<>();
        for (Setmeal record : records) {
            //拷贝相同信息
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(record, setmealDto);
            //查套餐名
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }
            //加入集合
            newRecords.add(setmealDto);
        }
        setmealDtoPage.setRecords(newRecords);

        //现在返回的数据类型就和前端需要的匹配上了，能显示分类名了。
        return R.success(setmealDtoPage);
    }

    /**
     * 单个/批量删除套餐,只能删停售的
     * @param ids
     * @return
     */
    @DeleteMapping
    //allEntries = true,清除setmealCache缓存分组下所有key以及对应值
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("删除套餐，ids={}", ids);

        setmealService.deleteWithDish(ids);

        String message;
        if (ids.size() > 1) message = "批量删除套餐成功";
        else message = "删除套餐成功";
        return R.success(message);
    }

    /**
     * 查询某类下所有套餐
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    //如果缓存命中,则返回缓存数据,否则访问数据库并将返回值存入缓存,R要实现序列化否则存入redis报错
    //可惜这样写弄不了Log.info提示缓存命中了,而且缓存命中的话里面的Log.info也会跳过
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        log.info("查询某类所有套餐,setmeal={}", setmeal);

        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        wrapper.eq(Setmeal::getStatus, 1);
        wrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(wrapper);

        return R.success(list);
    }

    /**
     * 套餐的单个/批量禁售/启售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    //allEntries = true,清除setmealCache缓存分组下所有key以及对应值
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("修改套餐售货状态,status={},ids.size()={}", status, ids.size());

        //update setmeal set status = {status} where id in {ids}
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(ids.size() > 0, Setmeal::getId, ids);
        Setmeal updateStatus = new Setmeal();
        updateStatus.setStatus(status);
        setmealService.update(updateStatus, wrapper);

        String message;
        if (ids.size() > 1)
            message = "批量修改售货状态成功";
        else
            message = "修改售货状态成功";
        return R.success(message);
    }
}
